import React, { useEffect, useRef, useState } from 'react'
import {Table,Button,Modal,Switch} from 'antd'
import {EditOutlined,DeleteOutlined,ExclamationCircleOutlined} from '@ant-design/icons'
import axios from 'axios'
import UserForm from '../../../components/user-manage/UserForm'
const { confirm } = Modal;

export default function RightList() {
  const[dataSource,setDataSource]=useState([])
  const [isAddVisible, setIsAddVisible] = useState(false);
  const [isUpdateVisible, setisUpdateVisible] = useState(false);
  const [isUpdateDisabled, setisUpdateDisabled] = useState(false);
  const [roleList, setRoleList] = useState([]);
  const [regionList, setRegionList] = useState([]);
  const [current,setCurrent]=useState(null)
  const addForm=useRef(null)
  const updateForm=useRef(null)
  // console.log(updateForm);


const {roleId,region,username}=JSON.parse(localStorage.getItem('token'))
  useEffect(()=>{
    const roleObj={
      "1":"superAdmin",
      "2":'admin',
      "3":"editor"
    }
    axios.get("http://localhost:8000/users?_expand=role").then(res=>{
        const list=res.data
        setDataSource(roleObj[roleId]==='superAdmin'?list:[
          ...list.filter(item=>item.username===username),
          ...list.filter(item=>item.region===region&& roleObj[item.roleId]==="editor")])
    })
  },[roleId,region,username])
  useEffect(()=>{
    axios.get("http://localhost:8000/regions").then(res=>{
        const list=res.data
        setRegionList(list)
    })
  },[])
  useEffect(()=>{
    axios.get("http://localhost:8000/roles").then(res=>{
        const list=res.data
        setRoleList(list)
    })
  },[])
// console.log(dataSource);
// console.log(regionList);

const addFormOK=()=>{
  // 对数据进行校验，校验成功过就走成功分支，失败就失败分支 
  addForm.current.validateFields().then(value=>{
   setIsAddVisible(false)
  //  重置表单
   addForm.current.resetFields()
  axios.post(`http://localhost:8000/users`,{
   ...value,
    "roleState": true,
    "default": false,
  }).then(res=>{
    // console.log(res.data);
    // setDataSource([...dataSource,res.data])
    // 由于role的值是连表获取出来的，刚开始只能获取一次，这边是调用users表，所以需要自己添加role
    // 首先过滤掉roleList中item.id等于value.roleId，然后获取第一个数组值
     setDataSource([...dataSource,{...res.data,role:roleList.filter(item=>item.id===value.roleId)[0]}])
  })
  }).catch(err=>{
    console.log(err);
  })
}
const updateFormOK=()=>{
  // 验证表单数据
 updateForm.current.validateFields().then(value=>{
  // console.log(value);
  setisUpdateVisible(false)
  setDataSource(dataSource.map(item=>{
    if(item.id===current.id){
      return{
        ...item,
        ...value,
        role:roleList.filter(data=>data.id===value.roleId)[0]
      }
    }
    return item;
  }))
  setisUpdateDisabled(!isUpdateDisabled)
  axios.patch(`http://localhost:8000/users/${current.id}`,value)
 })
}
  const columns = [
    {
      title: '区域',
      dataIndex: 'region',
      render:(region)=> {
        return <b>{region===""?'全球':region}</b>
      },
      filters: [
        ...regionList.map(item=>({
          text:item.title,
          value:item.value
        })),
        {
          text:'全球',
          value:'全球'
        }

      ],
      onFilter: (value, item) =>{
        if(value==='全球'){
          return item.region===''
        }else{
          return item.region===value
        }
      } 
    },
    {
      title: '角色名称',
      dataIndex: 'role',
      render:(role)=>{
        return <b>{role.roleName}</b>
      }
    },
    {
      title: '用户名',
      dataIndex: 'username',
      render:(username)=>{
        return  <b>{username}</b>
      }
    },
    {
      title: '用户状态',
      dataIndex: 'roleState',
      render:(roleState,item)=>{
        return <Switch checked={roleState}  disabled={item.default} onChange={()=>handleChange(item)} ></Switch>
    }
    },
    {
      title: '操作',
      render:(item)=>{
        return <div>
           <Button danger shape="circle" onClick={()=>showDeleteConfirm(item)}  icon={<DeleteOutlined />}/>
            <Button type="primary" shape="circle" icon={<EditOutlined />} disabled={item.default}  onClick={()=>handleUpdate(item)}/>
        </div>  
      }
    },
  ];
  const handleChange = (item) => {
    item.roleState=!item.roleState
    setDataSource([...dataSource])
    axios.patch(`http://localhost:8000/users/${item.id}`,{
      roleState:item.roleState
    })
   };
   const handleUpdate=(item)=>{
    setisUpdateVisible(true)
    setTimeout(()=>{
      if(item.roleId===1){
        // 禁用
        setisUpdateDisabled(true)
      }else{
        setisUpdateDisabled(false)
        // 把当前点击的数据展示在表单中
        updateForm.current.setFieldsValue(item)
      }
       
      },0)
      setCurrent(item)
}
    
  const showDeleteConfirm = (item) => {
    confirm({
      title: '你确认要删除吗?',
      icon: <ExclamationCircleOutlined />,
      // content: 'Some descriptions',
      okType: 'danger',
      okText: '确认',
      cancelText: '取消',
      onOk() {
       deleteMethod(item)
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  const deleteMethod=(item)=>{
    // console.log(item)
    setDataSource(dataSource.filter(data=>data.id!==item.id))
    axios.delete(`http://localhost:8000/users/${item.id}`)
  }
  return (
    <div>
       <Button
        // onClick={handleAdd}
        type="primary"
        style={{
          marginBottom: 16,
        }}
        onClick={()=>{setIsAddVisible(true)}}
      >
       添加用户
      </Button>
      <Table dataSource={dataSource} columns={columns} pagination={{ pageSize:5}} rowKey={item=>item.id}/>;
      <Modal title="添加用户" open={isAddVisible} 
      onOk={()=>{
       addFormOK()
      }} 
      onCancel={()=>{setIsAddVisible(false)}}>
      <UserForm regionList={regionList} roleList={roleList} ref={addForm}/>
      </Modal>

      <Modal 
      visible={isUpdateVisible}
      title="更新用户" 
      okText='更新'
      cancelText='取消'
      onOk={()=>{
       updateFormOK()
      }} 
      onCancel={()=>{setisUpdateVisible(false)
                    setisUpdateDisabled(!isUpdateDisabled)
                  }}>
      <UserForm regionList={regionList} roleList={roleList} ref={updateForm} isUpdate={true} isUpdateDisabled={isUpdateDisabled}/>
      </Modal>
    </div>
  )
}
